<template>
  <div class="login-page">
    <!-- 登录方式选择 -->
    <div v-if="!showLoginForm" class="login-methods">
      <div class="method-title">选择登录方式</div>
      <div class="method-list">
        <div class="method-item" @click="onSelectMethod('2')">
          <div class="method-icon phone-icon">手机</div>
          <div class="method-text">手机号登录</div>
          <div class="method-arrow">></div>
        </div>
        <div class="method-item" @click="onSelectMethod('1')">
          <div class="method-icon email-icon">邮箱</div>
          <div class="method-text">邮箱密码登录</div>
          <div class="method-arrow">></div>
        </div>
      </div>
    </div>

    <!-- 手机号登录表单 -->
    <div v-if="showLoginForm && loginMethod === '2'" class="login-container">
      <div class="login-header">
        <div class="back-btn" @click="onBackToMethods">返回</div>
        <div class="login-title">手机号登录</div>
      </div>
      <div class="login-input">
        <div class="login-input-label">手机号</div>
        <input 
          class="login-input-input" 
          type="number" 
          maxlength="11" 
          placeholder="请输入手机号" 
          v-model="phone" 
          @input="onPhoneInput" 
        />
      </div>
      <div class="login-input">
        <div class="login-input-label">验证码</div>
        <input 
          class="login-input-input" 
          type="number" 
          maxlength="6" 
          placeholder="请输入验证码" 
          v-model="code" 
          @input="onCodeInput" 
        />
        <button 
          class="login-code-btn" 
          @click="onGetCode" 
          :disabled="codeBtnDisabled"
        >
          {{ codeBtnText }}
        </button>
      </div>
      <button class="login-confirm-btn" @click="onPhoneLogin">确认登录</button>
    </div>

    <!-- 邮箱密码登录表单 -->
    <div v-if="showLoginForm && loginMethod === '1'" class="login-container">
      <div class="login-header">
        <div class="back-btn" @click="onBackToMethods">返回</div>
        <div class="login-title">邮箱密码登录</div>
      </div>
      <div class="login-input">
        <div class="login-input-label">邮箱</div>
        <input 
          class="login-input-input" 
          type="text" 
          placeholder="请输入邮箱" 
          v-model="account" 
          @input="onEmailInput" 
        />
      </div>
      <div class="login-input">
        <div class="login-input-label">密码</div>
        <input 
          class="login-input-input" 
          type="password" 
          placeholder="请输入密码" 
          v-model="password" 
          @input="onPasswordInput" 
        />
      </div>
      <div class="login-options">
        <div class="forgot-password-link" @click="onForgotPassword">忘记密码？</div>
        <div class="register-link" @click="onSwitchToRegister">还没有账号？立即注册</div>
      </div>
      <button class="login-confirm-btn" @click="onEmailLogin">确认登录</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showLoadingToast, closeToast } from 'vant'
import { login, sendSmsCode } from '@/api/auth'
import { getUserInfo } from '@/api/user'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const userInfo = await getUserInfo()
    userStore.setUserInfo(userInfo)
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

// 响应式数据
const showLoginForm = ref(false)
const loginMethod = ref('') // '1' 邮箱, '2' 手机号

// 手机号登录
const phone = ref('')
const code = ref('')
const codeBtnText = ref('获取验证码')
const codeBtnDisabled = ref(false)
const codeCountdown = ref(60)
let codeTimer = null

// 邮箱登录
const account = ref('')
const password = ref('')

// 选择登录方式
const onSelectMethod = (method) => {
  loginMethod.value = method
  showLoginForm.value = true
}

// 返回登录方式选择
const onBackToMethods = () => {
  showLoginForm.value = false
  loginMethod.value = ''
  // 清空表单数据
  phone.value = ''
  code.value = ''
  account.value = ''
  password.value = ''
}

// 手机号输入
const onPhoneInput = (e) => {
  phone.value = e.target.value
}

// 验证码输入
const onCodeInput = (e) => {
  code.value = e.target.value
}

// 获取验证码
const onGetCode = async () => {
  if (codeBtnDisabled.value) return
  
  const phoneValue = phone.value
  if (!/^1[3-9]\d{9}$/.test(phoneValue)) {
    showToast('请输入有效手机号')
    return
  }
  
  try {
    const res = await sendSmsCode(phoneValue)
    if (res.code === 0) {
      showToast({
        type: 'success',
        message: '验证码已发送'
      })
      codeBtnDisabled.value = true
      codeBtnText.value = `${codeCountdown.value}s`
      startCodeTimer()
    } else {
      showToast(res.msg || '发送失败')
    }
  } catch (error) {
    showToast('发送失败')
  }
}

// 验证码倒计时
const startCodeTimer = () => {
  let count = codeCountdown.value
  codeBtnText.value = `${count}s`
  codeBtnDisabled.value = true
  
  codeTimer = setInterval(() => {
    count--
    if (count <= 0) {
      clearInterval(codeTimer)
      codeBtnText.value = '获取验证码'
      codeBtnDisabled.value = false
      codeCountdown.value = 60
    } else {
      codeBtnText.value = `${count}s`
      codeCountdown.value = count
    }
  }, 1000)
}

// 手机号登录
const onPhoneLogin = async () => {
  const phoneValue = phone.value
  const codeValue = code.value
  
  if (!/^1[3-9]\d{9}$/.test(phoneValue)) {
    showToast('请输入有效手机号')
    return
  }
  if (!/^\d{4,6}$/.test(codeValue)) {
    showToast('请输入正确验证码')
    return
  }

  showLoadingToast({
    message: '登录中...',
    forbidClick: true,
  })

  try {
    const res = await login({ 
      account: phoneValue, 
      password: codeValue, 
      type: loginMethod.value 
    })
    
    closeToast()
    
    if (res.error_code === 0) {
      // 保存token
      localStorage.setItem('token', res.token)
      userStore.setToken(res.token)
      
      // 获取用户信息
      await fetchUserInfo()
      
      showToast({
        type: 'success',
        message: '登录成功'
      })
      
      setTimeout(() => {
        router.push('/home')
      }, 800)
    } else {
      showToast(res.msg || '登录失败')
    }
  } catch (error) {
    closeToast()
    showToast('登录失败')
  }
}

// 邮箱输入
const onEmailInput = (e) => {
  account.value = e.target.value
}

// 密码输入
const onPasswordInput = (e) => {
  password.value = e.target.value
}

// 邮箱登录
const onEmailLogin = async () => {
  const accountValue = account.value
  const passwordValue = password.value
  
  if (!accountValue || !passwordValue) {
    showToast('请输入邮箱和密码')
    return
  }
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(accountValue)) {
    showToast('请输入有效邮箱')
    return
  }
  
  showLoadingToast({
    message: '登录中...',
    forbidClick: true,
  })

  try {
    const res = await login({ 
      account: accountValue, 
      password: passwordValue, 
      type: loginMethod.value 
    })
    
    closeToast()
    
    if (res.error_code === 0) {
      // 保存token
      localStorage.setItem('token', res.token)
      userStore.setToken(res.token)
      
      // 获取用户信息
      await fetchUserInfo()
      
      showToast({
        type: 'success',
        message: '登录成功'
      })
      
      setTimeout(() => {
        router.push('/home')
      }, 800)
    } else {
      showToast(res.message || '登录失败')
    }
  } catch (error) {
    closeToast()
    showToast('登录失败')
  }
}

// 切换到注册
const onSwitchToRegister = () => {
  router.push('/register')
}

// 忘记密码
const onForgotPassword = () => {
  router.push({
    path: '/forgot-password',
    query: { 
      method: loginMethod.value // 传递登录方式：1-邮箱，2-手机号
    }
  })
}

// 组件卸载时清理定时器
onUnmounted(() => {
  if (codeTimer) {
    clearInterval(codeTimer)
  }
})
</script>

<style lang="scss" scoped>
.login-page {
  background: #f3f4f6;
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 100vh;
  padding: 20px;
  box-sizing: border-box;
}

/* 登录方式选择 */
.login-methods {
  width: 100%;
  max-width: 400px;
  background: #fff;
  min-height: 300px;
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(119, 163, 149, 0.10);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  padding: 30px 20px 20px 20px;
  margin-top: 20px;
}

.method-title {
  font-size: 20px;
  font-weight: bold;
  color: #157658;
  margin-bottom: 30px;
}

.method-list {
  width: 100%;
}

.method-item {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 16px 12px;
  margin-bottom: 10px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.03);
  border: 1px solid #f0f0f0;
  transition: all 0.3s ease;
  cursor: pointer;
  
  &:hover {
    background: #f8f9fa;
    border-color: #157658;
  }
  
  &:active {
    background: #f8f9fa;
    border-color: #157658;
  }
}

.method-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
  color: #fff;
  margin-right: 12px;
}

.phone-icon {
  background: #157658;
}

.email-icon {
  background: #ff6b35;
}

.method-text {
  flex: 1;
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

.method-arrow {
  font-size: 16px;
  color: #999;
  font-weight: bold;
}

/* 登录表单 */
.login-container {
  width: 100%;
  max-width: 400px;
  background: #fff;
  min-height: 300px;
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(119, 163, 149, 0.10);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  padding: 30px 20px 20px 20px;
  margin-top: 20px;
}

.login-header {
  width: 100%;
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  position: relative;
}

.back-btn {
  position: absolute;
  left: 0;
  font-size: 16px;
  color: #157658;
  padding: 8px;
  cursor: pointer;
}

.login-title {
  flex: 1;
  font-size: 20px;
  font-weight: bold;
  color: #157658;
  text-align: center;
}

.login-input {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 0 12px;
  margin: 10px 0;
  height: 44px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.03);
  border: 1px solid #f0f0f0;
  position: relative;
  overflow: hidden;
}

.login-input-label {
  width: 60px;
  font-weight: bold;
  color: #222;
  font-size: 16px;
  margin-right: 8px;
  margin-left: 10px;
  flex-shrink: 0;
}

.login-input-input {
  flex: 1;
  border: none;
  outline: none;
  font-size: 16px;
  color: #333;
  background: transparent;
  padding: 8px 0;
  min-width: 0;
  max-width: calc(100% - 100px);
  
  &::placeholder {
    color: #999;
  }
  
  &:focus {
    border-bottom: 1px solid #007aff;
  }
}

.login-code-btn {
  width: 80px;
  height: 30px;
  background: #157658;
  color: #fff;
  border: none;
  border-radius: 6px;
  font-size: 13px;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 8px;
  flex-shrink: 0;
  white-space: nowrap;
  cursor: pointer;
  
  &:disabled {
    background: #ccc;
    cursor: not-allowed;
  }
}

.login-options {
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin: 10px 0;
}

.forgot-password-link {
  font-size: 14px;
  color: #157658;
  text-decoration: underline;
  cursor: pointer;
}

.register-link {
  font-size: 14px;
  color: #157658;
  text-decoration: underline;
  cursor: pointer;
}

.login-confirm-btn {
  width: 90%;
  height: 44px;
  background-color: #157658;
  color: #fff;
  border: none;
  border-radius: 8px;
  font-size: 18px;
  font-weight: bold;
  margin-top: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px 0 rgba(76, 207, 161, 0.10);
  letter-spacing: 2px;
  cursor: pointer;
  
  &:active {
    opacity: 0.85;
  }
}
</style> 